<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .out{
            width: 400px;
            height: 400px;
            background: #aef;
            display:flex;
            justify-content: center;
            align-items: center;
            margin: 0 auto;
            position:relative;
        }
        .inner{
            width: 100px;
            height: 100px;
            background: #cea;
            position:absolute;
        }
    </style>
</head>
<body>
    <div id="root"></div>
    <script src="../js/react.development.js"></script>
    <script src="../js/react-dom.development.js"></script>
    <script src="../js/babel.min.js"></script>

    <script type="text/babel">
        class App extends React.Component{
            render(){
                return <div className="out" ref={el => this.out = el} onMouseMove={this.handleMousemove}>
                        <div className='inner' ref={el => this.inner = el}></div>
                    </div>
            }

            handleMousemove = (e) => {
                //计算尺寸
                let x = e.clientX; // pageX
                //获取 out 元素距离左侧的偏移量
                let l = this.out.offsetLeft;
                //获取 inner 元素宽度的一般
                let w = this.inner.offsetWidth / 2;
                //计算最终的 left 
                let newLeft = x - l - w;
                //计算左侧边界
                if(newLeft <= 0) newLeft = 0;
                //设置宽度
                this.inner.style.left = newLeft + 'px';
            }
        }

        ReactDOM.render(<App />, document.querySelector("#root"));
    </script>
</body>
</html>